<template>
  <div class="home-content">
    <p class="recipePRO">{{sysName}}</p>
    <div class="content content1" v-if="screenWidth > 750">
      <div class="item" v-for="(item,index) in menuAllList" :key="index"
        v-if="item.meta.icon && (parseFloat(item.meta.state) === 1 || role == 'admin')" @click="handleJump(item)"
        v-show="item.path !== 'customPage'">
        <i :class="'iconfont' + item.meta.icon" v-if="item.meta.icon.indexOf('iconfont') == -1" :style="{color:item.meta.color}"></i>
        <i :class="item.meta.icon" v-if="item.meta.icon.indexOf('iconfont') > -1" :style="{color:item.meta.color}"></i>
        <span class="title">{{$t(item.meta.title)}}</span>
        <!-- <span class="title">_{{item.meta.title}}</span> -->
      </div>
    </div>
    <div class="content content2" v-else>
      <div class="item" v-for="(item,index) in menuAllList" :key="index"
        v-if="item.meta.icon && (parseFloat(item.meta.state) === 1 || role == 'admin')" @click="handleJump(item)"
        v-show="item.path !== 'customPage'">
        <i :class="'iconfont' + item.meta.icon" v-if="item.meta.icon.indexOf('iconfont') == -1" :style="{color:item.meta.color}"></i>
        <i :class="item.meta.icon" v-if="item.meta.icon.indexOf('iconfont') > -1" :style="{color:item.meta.color}"></i>
        <span class="title">{{$t(item.meta.title)}}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { userAdmin } from "@/api/userAdmin"
import { siteConfig } from '@/api/siteConfig'
export default {
  data () {
    return {
      menuList: [],
      tableData: [],
      menuAllList: [],
      screenWidth: document.body.clientWidth,
      role: "",
      sysName: '',
    }
  },
  computed: {
    onRoutes () {
      if (this.$route.meta.path) {
        return "/" + this.$route.meta.path.split("/")[1];
      } else {
        return "/" + this.$route.path.split("/")[1];
      }
    },
  },
  watch: {
    screenWidth (val) {
      if (!this.timer) {
        this.screenWidth = val
        this.timer = true
        setTimeout(() => {
          this.timer = false
        }, 400)
      }
    }
  },
  async created () {
    this.role = localStorage.getItem('userName')
    await this.cumLinksList()
    await this.findBasicConfig()
    this.onLayoutResize()
    this.findMenusByUser()
  },
  methods: {
    onLayoutResize () {
      const that = this
      window.onresize = () => {
        return (() => {
          window.screenWidth = document.body.clientWidth
          that.screenWidth = window.screenWidth
        })()
      }
    },
    findMenusByUser () {
      userAdmin.findMenusByUser().then(res => {
        if (res.code == 200) {
          let menusList = res.data.filter(item => item.menuType == 'M')
          let routerArr = JSON.parse(JSON.stringify(this.$router.options.routes[0].children))
          routerArr.forEach(item => {
            const indexTemp = menusList.findIndex(el => item.path == el.url)
            if (indexTemp > -1) {
              let children1 = menusList[indexTemp].children
              let children2 = item.children || []
              if (children1 && children1.length) {
                let onlyInMenusList = children1.filter(menuItem => {
                  const indexTemp = children2.findIndex(routerItem => routerItem.path === menuItem.url);
                  return indexTemp === -1;
                });
                if (onlyInMenusList.length) {
                  onlyInMenusList.forEach((item1, i) => {
                    if (item1) {
                      children2.push({
                        path: '/customPage?url=' + item1.url,
                        name: 'customPage',
                        component: () => import('@/page/customPage/index.vue'),
                        meta: {
                          title: item1.menuName,
                          icon: " icon-baobiao-xianxing",
                          url: item1.url,
                          index: new Date().getTime(),
                          state: item1.state
                        }

                      });

                      item.meta.children.push('/customPage')

                      this.$router.addRoute('customPage', {
                        path: '/customPage?url=' + item1.url,
                        name: 'customPage',
                        component: () => import('@/page/customPage/index.vue'),
                        meta: {
                          title: item1.name,
                          icon: " icon-baobiao-xianxing",
                          url: item1.url,
                          index: new Date().getTime(),
                          state: item1.state
                        },
                      });
                    }

                  });
                }
              } else {
                ////
                item.meta.state = menusList[indexTemp].state
              }

            } else {



              // children2.push({
              //     path: '/customPage?url='+item1.url,
              //     name: 'customPage',
              //     component: () => import('@/page/customPage/index.vue'),
              //     meta: {
              //         title: item1.menuName,
              //         icon: " icon-baobiao-xianxing",
              //         url:item1.url,
              //         index:new Date().getTime()
              //     }

              // });
            }
          })
          const missingItems = [];
          menusList.forEach(menuItem => {
            const indexTemp = routerArr.findIndex(item => item.path === menuItem.url);
            if (indexTemp === -1) {
              missingItems.push(menuItem);
            }
          });

          // const index = routerArr.findIndex(item => item.path == '/reportForm')
          missingItems.forEach((item, index) => {
            if (item.children && item.children.length) {
              routerArr.push({
                path: '/reportForm' + item.fid,
                name: 'reportForm' + item.fid,
                component: () => import('@/page/reportForm/index.vue'),
                meta: {
                  title: item.menuName,
                  icon: " icon-baobiao-xianxing",
                  children: ['/reportFormInfo'],
                  fid: item.fid,
                  url: item.url,
                  state: item.state
                },
                children: []
              })

              item.children.forEach(item1 => {
                const temp = {
                  path: '/customPage?url=' + item1.url,
                  name: 'customPage',
                  component: () => import('@/page/customPage/index.vue'),
                  meta: {
                    title: item1.menuName,
                    icon: " icon-baobiao-xianxing",
                    url: item1.url,
                    index: new Date().getTime(),
                    state: item1.state
                  }
                }

                routerArr.forEach(item2 => {
                  if (item2.meta.fid == item.fid) {
                    item2.children.push(temp)
                  }
                })

              })
            } else {
              const temp = {
                path: '/customPage?url=' + item.url,
                name: 'customPage',
                component: () => import('@/page/customPage/index.vue'),
                meta: {
                  title: item.menuName,
                  icon: " icon-baobiao-xianxing",
                  url: item.url,
                  index: new Date().getTime(),
                  state: item.state
                }
              }
              routerArr.push(temp)
            }
          })

          console.log(JSON.parse(JSON.stringify(routerArr)), 989898)
          // const index = routerArr.findIndex(item => item.path == '/reportForm')
          // const keyId = menusList.findIndex(item => item.url == '/reportForm')
          // if (index > -1) {
          //   routerArr[index].children = []
          //   this.tableData.forEach((item, key) => {
          //     if (menusList[keyId].children && menusList[keyId].children.length) {
          //       const el = menusList[keyId].children.find(item1 => item1.menuName == item.name)
          //       if (el) {
          //         const temp = {
          //           path: '/' + el.url.split('/')[1] + '/:id',
          //           name: el.url.split('/')[1] + '/:id',
          //           component: () => import('@/page/reportForm/reportFormInfo.vue'),
          //           meta: {
          //             title: item.name,
          //             icon: item.icon,
          //             url: item.url,
          //             index: key,
          //             color: "#8232C8"
          //           }
          //         }
          //         routerArr[index].children.push(temp)
          //         this.$router.addRoute('reportForm', {
          //           path: '/' + el.url.split('/')[1] + '/:id',
          //           name: el.url.split('/')[1] + '/:id',
          //           component: () => import('@/page/reportForm/reportFormInfo.vue'),
          //           meta: {
          //             title: item.name,
          //             icon: item.icon,
          //             url: item.url,
          //             index: key,
          //             color: "#8232C8"
          //           },
          //         });
          //       }
          //     }
          //   })
          // }
          console.log(JSON.parse(JSON.stringify(menusList)), 787878)
          let menuListArr = []
          routerArr.forEach(item => {
            menusList.forEach(el => {
              if (item.path == el.url || item.meta.url == el.url) {
                item.meta.title = item.meta.title
                item.meta.orderNum = parseInt(el.orderNum)
                menuListArr.push(item)
              }
            })
          })
          console.log(JSON.parse(JSON.stringify(menuListArr)), 111)
          console.log(JSON.parse(JSON.stringify(menusList)), 222)
          menusList.forEach(item => {
            menuListArr.forEach(el => {
              if (item.url == el.path) {
                if (el.children) {
                  el.children = el.children.filter(item1 => {
                    const index = item.children.findIndex(el1 => {
                      if (item1.path.split('/')[1] == el1.url.split('/')[1]) {
                        return item1.path.split('/')[1] == el1.url.split('/')[1]
                      } else {
                        if (item1.name == 'customPage') {
                          if (item1.path && item1.path.indexOf('?') > -1) {
                            let urlPath = item1.path
                            let queryPart = urlPath.split('?')[1];
                            let queryValue = queryPart.split('=')[1];
                            let url = decodeURIComponent(queryValue)
                            if (url == el1.url) {
                              return el1
                            }
                          }

                        }
                      }

                    })
                    if (index > -1) {
                      item1.meta.state = item.children[index].state
                      return item1
                    }
                  })
                }

              }
            })
          })



          this.menuList = menuListArr.sort(this.compare('orderNum'));
          console.log(JSON.parse(JSON.stringify(this.menuList)), 8888)

          let menuAllList = []
          this.menuList.forEach(item => {
            if (item.children && item.children.length > 0) {
              menuAllList.push(...item.children)
            } else {
              menuAllList.push(item)
            }

          })
          this.menuAllList = menuAllList
          console.log(JSON.parse(JSON.stringify(this.menuAllList)), 777)
        }
      })
    },
    compare (propertyName) {
      return function (object1, object2) {
        var value1 = object1.meta[propertyName];
        var value2 = object2.meta[propertyName];
        if (value2 < value1) {
          return 1;
        } else if (value2 > value1) {
          return -1;
        } else {
          return 0;
        }
      }
    },
    cumLinksList () {
      userAdmin.cumLinksList({}).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.rows
        }
      })
    },
    handleJump (item) {
      console.log(item)
      if (item.name == 'reportFormInfo/:id') {
        this.$router.push({
          path: item.path.split('/')[1] + '/' + item.meta.index
        })
      } else if (item.name == 'customPage') {
        // this.$router.push({
        //   path: item.path
        // })
        if (item.path.indexOf('ReportServer') > -1) {
          let index = item.path.indexOf('url=')
          let urlNew = item.path.substring(index + 4)
          window.open(urlNew, '_blank');
        }
      } else {
        this.$router.push({
          name: item.name
        })
        // this.$router.resolve({ path: item.url })
        // window.open(item.url, '_blank');
      }

    },
    buildMenuTree (menuItems) {
      const menuMap = new Map();
      const topLevelMenus = [];

      // 遍历菜单项，并将每个菜单项及其子项存储到map中
      for (const item of menuItems) {
        if (!menuMap.has(item.fid)) {
          menuMap.set(item.fid, { ...item, children: [] });
        }

        // 如果当前菜单项有parentId且其不在map中，则创建一个新的顶级菜单项
        if (item.parentId && !menuMap.has(item.parentId)) {
          menuMap.set(item.parentId, { fid: item.parentId, name: '未知顶级菜单（自动生成）', parentId: null, children: [] });
        }

        // 将当前菜单项添加到其父节点的children数组中
        const parentItem = menuMap.get(item.parentId);
        if (parentItem) {
          parentItem.children.push({ ...item });
        }
      }

      // 提取所有顶级菜单项（即parentId为null的菜单项）
      menuMap.forEach((value, key) => {
        if (!value.parentId) {
          topLevelMenus.push(value);
        }
      });

      return topLevelMenus;
    },
    findBasicConfig () {
      siteConfig.findBasicConfig().then(res => {
        if (res.code == 200) {
          this.sysName = res.data.sysName
          console.log(this.formData)
        }
      })
    },

  }
}
</script>

<style scoped>
.home-content {
  height: 100%;
  position: relative;
}
.imageTitle {
  position: absolute;
  bottom: 30px;
  right: 30px;
}
.home-content img {
  width: 420px;
}
.welcome {
  font-size: 24px;
  color: #999999;
  margin-top: 25px;
  text-align: center;
}
.menuList {
  width: 1000px;
  height: 300px;
  /* background: red; */
  margin: auto;
}
.content {
  display: flex;
  flex-wrap: wrap;
  max-width: 1000px;
  /* background: red; */
  margin: auto;
}

.item {
  margin: 5px;
  width: calc(100% / 5 - 10px);
  /* padding-top: calc((100% / 5 - 135px)/2); */
  padding-bottom: calc(100% / 5 - 10px);
  background-color: #eff1f4;
  text-align: center;
  position: relative;
  cursor: pointer;
  height: 0;
}
.content1 .item {
  margin: 5px;
  width: calc(100% / 5 - 10px);
  padding-top: calc((100% / 5 - 25px) / 2);
  padding-bottom: calc((100% / 5 + 5px) / 2);
  background-color: #eff1f4;
  text-align: center;
  position: relative;
  cursor: pointer;
}
.content1 .item i {
  font-size: 4.5rem !important;
  position: absolute;
  left: 50%;
  top: 37%;
  transform: translate(-50%, -50%);
}
.title {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  display: inline-block;
  height: 50px;
  background: #e2e6eb;
  line-height: 50px;
}
.imgBox {
  text-align: center;
  width: calc(100% - 100px);
  height: 0;
  padding-top: calc(100% - 100px);
  margin: auto;
  position: absolute;
  left: 50%;
  top: 39%;
  transform: translate(-50%, -50%);
  border-radius: 50%;
  color: #fff;
}
.item i {
  font-size: 5rem;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  /* font-weight: bold; */
}
.recipePRO {
  line-height: 50px;
  text-align: center;
  font-weight: 900;
  font-size: 20px;
}
.content2 .item {
  margin: 5px;
  width: calc(100% / 3 - 10px);
  padding-top: calc((100% / 3 - 25px) / 2);
  padding-bottom: calc((100% / 3 + 5px) / 2);
  background-color: #eff1f4;
  text-align: center;
  position: relative;
  cursor: pointer;
}
.content2 .item i {
  font-size: 45px !important;
  position: absolute;
  left: 50%;
  top: 37%;
  transform: translate(-50%, -50%);
}
.content2 .title {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  display: inline-block;
  height: 30px;
  background: #e2e6eb;
  line-height: 30px;
  font-size: 16px !important;
}
.content {
  width: 100% !important;
}
@media only screen and (max-width: 750px) {
  .content2 .item i {
    font-size: 55px !important;
  }
}
@media only screen and (max-width: 500px) {
  .content2 .item i {
    font-size: 45px !important;
  }
}
@media only screen and (max-width: 400px) {
  .content2 .item i {
    font-size: 35px !important;
  }
}
</style>
